/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.ubc.icapture.genapha.actions;

import ca.ubc.icapture.genapha.forms.SnpGeneForm;
import icapture.SQLMgr;
import icapture.beans.DB.Gene;
import icapture.genapha.GenaphaTools;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.read.biff.BiffException;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.Action;
import jxl.*;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.biomoby.services.ncbi.NCBIJobManager;
import org.biomoby.services.ncbi.jobs.GeneInformationByEntrezGeneIdFromXML;

/**
 *
 * @author ATan1
 */
public class PathwayGeneAction extends Action {

    private HashMap<String, ArrayList<Gene>> pathwayGene = new HashMap();

    @Override
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) {
        ActionErrors errors = new ActionErrors();
        ActionForward forward = new ActionForward();
        final SnpGeneForm snpGeneForm = (SnpGeneForm) form;
        pathwayGene.clear();
        if (snpGeneForm.getSubmitType().isEmpty()) {
            return mapping.findForward("display");
        }
        if (snpGeneForm.getUseTextarea().equals("text")) {
            ByteArrayInputStream bais = new ByteArrayInputStream(snpGeneForm.getTextInput().getBytes());
            ArrayList<String> inputContents = GenaphaTools.readFile(bais);
            try {
                readCSVFile(inputContents);
            } catch (Exception ex) {
                Logger.getLogger(PathwayGeneAction.class.getName()).log(Level.SEVERE, null, ex);
                errors.add("snpGene", new ActionMessage("snpGene.error.errorReadingText"));
                forward = mapping.findForward("error");
                saveErrors(request, errors);
                return forward;
            }
            forward = mapping.findForward("next");
        } else if (snpGeneForm.getFile() != null) {
            try {
                readExcelFile(snpGeneForm.getFile().getInputStream());

                //dirty way to readin file if not excel
            } catch (Exception e) {
                try {
                    ArrayList<String> fileContents = GenaphaTools.readFile(snpGeneForm.getFile().getInputStream());
                    readCSVFile(fileContents);
                } catch (Exception ex) {
                    Logger.getLogger(PathwayGeneAction.class.getName()).log(Level.SEVERE, null, ex);
                    errors.add("snpGene", new ActionMessage("geneSnp.error.readingFile"));
                    forward = mapping.findForward("error");
                    saveErrors(request, errors);
                    return forward;
                }
            }
            forward = mapping.findForward("next");
        }
        if (pathwayGene.size() > 0) {
            snpGeneForm.setPathGeneHash(pathwayGene);
            request.getSession().setAttribute("snpGeneForm", snpGeneForm);
        }
        if (snpGeneForm.getExcel()) {
            forward = mapping.findForward("export");
        }
        return forward;
    }

    private void readExcelFile(InputStream in) throws IOException, BiffException {
        Workbook wb = Workbook.getWorkbook(in);
        Sheet sheet = wb.getSheet(0);
        ArrayList<String> pathwayList = new ArrayList<String>();
        Cell[] col = sheet.getColumn(0);
        for (int i = 0; i < col.length; ++i) {
            pathwayList.add(col[i].getContents().trim());
        }
        try {
            getPathwayToGene(pathwayList);
        } catch (Exception e) {
        }
    }

    private void readCSVFile(ArrayList<String> fileContents) throws Exception {
        ArrayList<String> pathwayList = new ArrayList<String>();
        for (String line : fileContents) {
            pathwayList.add(line.trim());
        }
        getPathwayToGene(pathwayList);
    }

    public void getPathwayToGene(ArrayList<String> pathwayList) throws Exception {
        ArrayList<String> allNCBI = new ArrayList();
        for (String pathName : pathwayList) {
            ArrayList<Gene> tmpGeneList = SQLMgr.getGenesWithKeggPathways(pathName);
            pathwayGene.put(pathName, tmpGeneList);
            for (Gene tmpGene : tmpGeneList) {
                allNCBI.add(String.valueOf(tmpGene.getEntrezGeneID()));
            }
        }

        GeneInformationByEntrezGeneIdFromXML geneInformationByEntrezGeneIdFromXML = new GeneInformationByEntrezGeneIdFromXML();
        geneInformationByEntrezGeneIdFromXML.setGeneIdList(allNCBI);

        NCBIJobManager.runJob(geneInformationByEntrezGeneIdFromXML);

        HashMap<String, String[]> geneMap = geneInformationByEntrezGeneIdFromXML.getGeneMap();
        for (ArrayList<Gene> tmpGeneList : pathwayGene.values()) {
            for (Gene tmpGene : tmpGeneList) {
                String[] geneInfo = geneMap.get(String.valueOf(tmpGene.getEntrezGeneID()));
                tmpGene.setName(geneInfo[0]);
            }
        }
    }
}
